import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function handler(req, res) {
  const { method } = req;

  if (method === "GET") {
    const { id } = req.query;
    if (id) {
      try {
        const user = await prisma.user.findUnique({
          where: { id: parseInt(id) },
          include: { roles: true }, // Include associated roles
        });

        if (!user) {
          return res.status(404).json({ error: "用户未找到" });
        }
        return res.status(200).json(user);
      } catch (error) {
        console.log("error --- ", error);
        return res.status(500).json({ error: "获取用户失败" });
      }
    } else {
      // Query all users with associated roles
      const users = await prisma.user.findMany({
        include: { roles: true }, // Include associated roles
      });
      return res.status(200).json(users);
    }
  }

  if (method === "POST") {
    // 创建新用户
    const { name, email, password, roles } = req.body; // Expecting roles to be an array of role IDs
    console.log({ name, email, password, roles });
    try {
      const newUser = await prisma.user.create({
        data: {
          name,
          email,
          password,
          roles: {
            create: roles.map((roleId) => ({ roleId })), // Associate roles
          },
        },
      });
      return res.status(201).json(newUser);
    } catch (error) {
      console.log("error --- ", error);
      return res.status(500).json({ error: "创建用户失败" });
    }
  }

  if (method === "PUT") {
    const { id } = req.query;
    // 更新用户
    if (!id) {
      return res.status(400).json({ error: "缺少用户 ID" });
    }
    const { name, email, password, roles } = req.body; // Expecting roles to be an array of role IDs
    try {
      const updatedUser = await prisma.user.update({
        where: { id: parseInt(id) },
        data: {
          name,
          email,
          password,
          roles: {
            deleteMany: {}, // Clear existing roles
            create: roles.map((roleId) => ({ roleId })), // Add new roles
          },
        },
      });
      return res.status(200).json(updatedUser);
    } catch (error) {
      console.log("error --- ", error);
      return res.status(500).json({ error: "更新用户失败" });
    }
  }

  if (method === "DELETE") {
    const { id } = req.query;
    // 删除用户
    if (!id) {
      return res.status(400).json({ error: "缺少用户 ID" });
    }
    try {
      await prisma.user.delete({
        where: { id: parseInt(id) },
      });
      return res.status(204).end(); // No Content
    } catch (error) {
      return res.status(500).json({ error: "删除用户失败" });
    }
  }

  // 处理不支持的方法
  res.setHeader("Allow", ["GET", "POST", "PUT", "DELETE"]);
  res.status(405).end(`Method ${method} Not Allowed`);
}
